// 处理提问的路由

const data = {
    prompt: '你好',
    userId: '#/chat/1691897858045',
    network: false,
    system: '',
    withoutContext: false,
    stream: false,
}

const url = 'https://api.binjie.fun/api/generateStream'

async function getAnswer(prompt) {
    data.prompt = prompt
    const resp = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            referer: 'https://c.binjie.fun/',
            origin: 'https://c.binjie.fun',
        },
        body: JSON.stringify(data),
    })
    const json = await resp.text()
    return json
}

module.exports = async (req, res) => {
    // 从body解析用户id和prompt
    let { prompt } = req.body
    let id = req.id
    // 从数据库中查询用户是否存在
    let user = req.db.get('users').find({ id }).value()
    // 用户不存在
    if (!user) {
        res.send({
            success: false,
            msg: '用户不存在',
        })
        return
    }
    // 用户存在
    // 检查剩余提问次数
    if (user.remain <= 0) {
        res.send({
            success: false,
            msg: '提问次数不足',
        })
        return
    }
    // prompt不能为空
    if (!prompt || prompt.trim() === '') {
        res.send({
            success: false,
            msg: '提问不能为空',
        })
        return
    }
    // 获取回答

    // 检查历史提问中是否存在回答内容
    let answer

    answer = req.db.get('questions').find({ prompt }).value()

    if (answer) {
        answer = answer.answer
    } else {
        try {
            answer = await getAnswer(prompt)
        } catch (e) {
            console.log(e)
            res.status(500).send({
                success: false,
                msg: '服务器错误',
            })
            return
        }
    }

    // 提问次数减1
    req.db
        .get('users')
        .find({ id })
        .assign({
            remain: user.remain - 1,
        })
        .write()

    // 生成提问记录
    const answerLog = {
        id: req.db.get('questions').value().length + 1,
        prompt,
        answer,
        date: Date.now().toString(),
        userId: id,
    }

    // 把提问记录插入到数据库
    req.db.get('questions').push(answerLog).write()

    // 返回回答
    res.send({
        success: true,
        msg: '提问成功',
        data: {
            answer,
        },
    })
}
